package com.comba.patch.tool.controller;

import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.comba.patch.tool.conf.Configuration;
import com.comba.patch.tool.utils.AlertUtils;
import com.google.common.base.Joiner;
import com.google.common.io.LineReader;

import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;

public class PatchFileFilterConfigController implements Initializable {
	private static final Logger LOGGER = LoggerFactory.getLogger(PatchFileFilterConfigController.class);
	private Stage stage;

	@FXML
	private TextArea configArea;

	public void handleCancel(Event event) {
		this.stage.close();
	}

	public void handleOk() {
		try {
			String content = this.configArea.getText();
			LineReader lineReader = new LineReader(new StringReader(content));
			String line = null;
			Configuration.getInstance().getExcludeFilePatterns().clear();
			while((line=lineReader.readLine()) != null) {
				if(StringUtils.isNotBlank(line)) {
					Configuration.getInstance().addtExcludeFilePattern(StringUtils.trim(line));
				}
			}
			this.stage.close();
		} catch (IOException e) {
			String msg = "配置保存失败";
			LOGGER.error(msg, e);
			AlertUtils.exception(msg, e);
		}
	}

	public void handleSave() {
		this.handleOk();

		//TODO 保存至Preference
	}

	public void setStage(Stage stage) {
		this.stage = stage;
	}


	@Override
	public void initialize(URL location, ResourceBundle resources) {
		List<String> excludeFilePatterns = Configuration.getInstance().getExcludeFilePatterns();
		String content = Joiner.on('\n').join(excludeFilePatterns);
		this.configArea.setText(content);
	}

}
